import time

from daterange_filter.filter import DateRangeFilter
from django.contrib import admin

# Register your models here.
from django.contrib.auth.models import User
from django.db.models import F
from django.utils import timezone
from django.utils.html import format_html

from app_server.models import Assignment, AssignPics, AssignClass, UserDetail, StudentSelect, UserScore, UserLogin


class AssignmentInline(admin.TabularInline):
    model = AssignPics
    fk_name = "belong_assign"


class UserScoreInline(admin.TabularInline):
    model = UserScore


class AssignmentFilter(admin.SimpleListFilter):
    title = '是否已经结束'
    parameter_name = 'over'

    def lookups(self, request, model_admin):
        return (
            ('0', '进行中'),
            ('1', '已结束'),
        )

    def queryset(self, request, queryset):
        if self.value() == '0':
            return queryset.filter(activity_time__gte=timezone.now())  # F Q 语句
        if self.value() == '1':
            return queryset.filter(activity_time__lt=timezone.now())


class AssignmentAdmin(admin.ModelAdmin):
    inlines = [
        AssignmentInline,
    ]

    list_display = ('name', 'belong_class', 'belong_user', 'credit', 'create_time', 'activity_time', 'site')
    readonly_fields = ('belong_user',)
    list_filter = (
        ('create_time', DateRangeFilter), ('activity_time', DateRangeFilter), AssignmentFilter,
        'belong_class__class_name',)
    # = ('create_time', )
    date_hierarchy = 'create_time'

    # def time_over_or_not(self, obj):
    #     return format_html('<span style="color:%s">%s</span>' % ('red' if obj.activity_time < timezone.now() else 'green', timezone.template_localtime(obj.activity_time).strftime("%Y年%m月%d日 %H:%M")))
    # time_over_or_not.short_description = "活动时间"

    def save_model(self, request, obj, form, change):
        obj.belong_user = request.user
        obj.save()


class UserDetailFilter(admin.SimpleListFilter):
    title = '是否达标'
    parameter_name = 'finish'

    def lookups(self, request, model_admin):
        return (
            ('0', '未达标'),
            ('1', '已达标'),
        )

    def queryset(self, request, queryset):
        if self.value() == '0':
            return queryset.filter(has_credit__lt=F('require_credit'))  # F Q 语句
        if self.value() == '1':
            return queryset.filter(has_credit__gte=F('require_credit'))


class UserDetailAdmin(admin.ModelAdmin):
    list_display = ['to_user', 'has_credit', 'require_credit']

    list_filter = (UserDetailFilter,)

    inlines = [UserScoreInline, ]


def change_status_finish(modeladmin, request, queryset):
    """
    学生听课完成后修改方法。
    若学生已经完成，则无需操作。
    若学生尚未完成，则修改为完成，并增加总分数和科目分数。
    若总分数表，和科目分数表不存在，则创建。
    """
    for q in queryset:
        credit = q.select_lessons.credit
        lesson_class = q.select_lessons.belong_class
        user = q.belong_user
        if q.status == 1:
            pass
        else:
            q.status = 1
            ud, has_it = UserDetail.objects.get_or_create(to_user=user)
            ud.has_credit = F("has_credit") + credit
            us, has_it = UserScore.objects.get_or_create(to_user_detail=ud, to_assign_class=lesson_class)
            us.has_credit = F("has_credit") + credit
            ud.save()
            us.save()
            q.save()


change_status_finish.short_description = '选中用户任务完成'


def change_status_fail(modeladmin, request, queryset):
    """
    原理同上，反过来
    只有在已完成情况下，需要 减去成绩。
    否则直接改为未完成即可
    """
    for q in queryset:
        credit = -q.select_lessons.credit
        lesson_class = q.select_lessons.belong_class
        user = q.belong_user
        if q.status == 1:
            ud, has_it = UserDetail.objects.get_or_create(to_user=user)
            ud.has_credit = F("has_credit") + credit
            us, has_it = UserScore.objects.get_or_create(to_user_detail=ud, to_assign_class=lesson_class)
            us.has_credit = F("has_credit") + credit
            ud.save()
            us.save()
            q.save()

        q.status = -1
        q.save()


change_status_fail.short_description = '选中用户任务失败'


class StudentSelectAdmin(admin.ModelAdmin):
    actions = (change_status_finish, change_status_fail)
    search_fields = ['belong_user__username', 'select_lessons__name']
    list_display = ['belong_user', 'select_lessons', 'status']
    list_filter = ['status']
    readonly_fields = ["status", ]


class AssignClassAdmin(admin.ModelAdmin):
    list_display = ('class_name', 'assign_class_color',)

    def assign_class_color(self, obj):
        # return format_html('<lable style="background:%s; width:50px; height:16px; display:inline-block;">x</lable><span style="padding-left:10px;">%s</span>' % (obj.color, obj.color))
        return format_html(
            '<lable style="background:%s; color:%s">%s</lable><span style="padding-left:10px;">%s</span>' % (
                obj.color, obj.color, obj.color, obj.color,))

    assign_class_color.short_description = "类别颜色"


class UserScoreAdmin(admin.ModelAdmin):
    list_display = ("to_user_detail", "to_assign_class", "has_credit")


admin.site.register(Assignment, AssignmentAdmin)
admin.site.register(AssignClass, AssignClassAdmin)
admin.site.register(UserDetail, UserDetailAdmin)
admin.site.register(StudentSelect, StudentSelectAdmin)
admin.site.register(UserScore, UserScoreAdmin)
admin.site.register(UserLogin)

admin.site.site_header = '高校第二课堂成绩管理'
admin.site.site_title = "高校第二课堂成绩管理"
admin.AdminSite.index_title = ""
admin.AdminSite.site_url = ""
